package com.example.demo.controller;

import com.example.demo.pojo.Result;
import com.example.demo.pojo.User;
import com.example.demo.pojo.dto.UserDto;
import com.example.demo.service.IUserService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

@RestController  //接口方法返回对象转换为json文本
@RequestMapping ("/user") //localhost:8080/user
public class UserController {
    @Autowired
    private IUserService userService;

    // 增加
    @PostMapping ()
    public Result add(@Validated @RequestBody(required = false) UserDto user){
        if (user == null) {
            return Result.error();
        }
        User userNew=  userService.add(user);
        return Result.success(userNew);
    }
    // 查询
    @GetMapping ("/{userId}")
    public Result query(@PathVariable Integer userId){
        User user= userService.getUser(userId);
        return Result.success(user);
    }

    // 修改
    @PutMapping ("/update")
    public Result edit(@Validated @RequestBody UserDto user){
        User userNew=  userService.edit(user);
        return Result.success(userNew);
    }
    // 删除
    @DeleteMapping ("/{userId}")  // 修改：为 @DeleteMapping 添加路径参数
    public Result delete(@PathVariable Integer userId){
        userService.delete(userId);
        return Result.success();
    }
}